#include "dht11.h"

u8 dht11_data[5]={0,0,0,0,0};

void dht11_pin_mode(u8 select){
	GPIO_InitTypeDef GPIO_InitStructure;
	
	if(select)
	{
		GPIO_InitStructure.GPIO_Pin = DHT11_PIN;
		GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
		GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	}
	else
	{
		GPIO_InitStructure.GPIO_Pin =  DHT11_PIN;
		GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
	}
	GPIO_Init(DHT11_PORT, &GPIO_InitStructure);
}

void dht11_begain(){
	dht11_pin_mode(OUT);
	DHT11_Low;
	delay_ms(20);
	DHT11_High;
	delay_us(13);
}

u8 dht11_ack(){
	u8 temp=0;
	dht11_pin_mode(IN);
	
	while((DHT11_PIN_in == 1) && (temp<100) ){
		delay_us(1);
		temp++;
	}
	if(temp >= 100){
		return 1;
	}else{
		temp=0;
	}
	
	while((DHT11_PIN_in == 0) && (temp<100) ){
		delay_us(1);
		temp++;
	}
	if(temp >= 100){
		return 1;
	}
	
	return 0;
	
}

u8 dht11_init(){
	my_gpioinit_out(DHT11_PORT_CLK,DHT11_PORT,GPIO_Mode_Out_PP,DHT11_PIN,GPIO_Speed_50MHz);
	DHT11_PIN_out=1;
	dht11_begain();
	
	return dht11_ack();
}

u8 dht11_readbit(){
	u8 temp=0;
	while((DHT11_PIN_in == 1) && (temp<100) ){
		delay_us(1);
		temp++;
	}
	temp=0;
	while((DHT11_PIN_in == 0) && (temp<100) ){
		delay_us(1);
		temp++;
	}
	delay_us(40);
	if(DHT11_PIN_in == 1){
		return 1;
	}else{
		return 0;
	}
	
}

u8 dht11_readbyte(){
	u8 i,dat;
	dat=0;
	for (i=0;i<8;i++) 
	{
		dat<<=1; 
		dat|=dht11_readbit();
	}						    
	return dat;
}

u8 dht11_readdata(){

	u8 i=0,temp=0;
	dht11_begain();
	if(dht11_ack()){
		return 1;
	}else{
		
		for(i=0;i<5;i++){
			dht11_data[i]=dht11_readbyte();
		}
		
		for(i=0;i<4;i++){
			temp+=dht11_data[i];
		}
		if(temp == dht11_data[4]){
			return 0;
		}else{
			return 3;
		}
		
	}
	
	
}